package com.fy.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fy.common.config.AppConfig;
import com.fy.common.constants.Constants;
import com.fy.common.constants.MessageConstant;
import com.fy.ex.ConditionException;
import com.fy.ex.handler.ExceptionHandler;
import com.fy.mapper.*;
import com.fy.pojo.dto.admin.AdminLoadUserListDTO;
import com.fy.pojo.entity.*;
import com.fy.pojo.enums.AccountStatusEnum;
import com.fy.pojo.enums.FileDelFlagEnums;
import com.fy.pojo.enums.FileFolderTypeEnums;
import com.fy.pojo.vo.activity.ActiveUserVO;
import com.fy.pojo.vo.admin.AdminLoadUserListVO;
import com.fy.pojo.vo.other.CheckInVO;
import com.fy.pojo.vo.user.LoginUserVO;
import com.fy.pojo.vo.user.UserInfoVO;
import com.fy.pojo.vo.user.UserProfileVO;
import com.fy.pojo.vo.user.UserSpaceVO;
import com.fy.service.UserService;
import com.fy.utils.*;
import com.fy.utils.aliyunUtils.AliOssFileOperation;
import com.fy.utils.result.PageResult;
import com.fy.utils.result.Result;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import static cn.hutool.core.bean.BeanUtil.copyProperties;

@Slf4j
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    private JavaMailSender javaMailSender;

    @Autowired
    private FileInfoMapper fileInfoMapper;

    @Autowired
    private AliOssFileOperation aliOssFileOperation;

    @Autowired
    private AppConfig appConfig;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private EmailMapper emailMapper;

    @Autowired
    private EmailCodeSend emailCodeSend;

    @Autowired
    private RedisUtils redisUtils;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private PositionMapper positionMapper;

    @Autowired
    private AdminSysMapper adminSysMapper;

    @Autowired
    private UserSignMapper userSignMapper;

    /***
     * 发送邮箱验证码
     *
     * @param email
     */
    @Override
    @Transactional(rollbackFor = { ConditionException.class })
    public void sendEmailCheckCode(String email) {
        String code = StringTools.getRandomNumber(6);
        log.info("邮箱验证码为:{}", code);

        javaMailSender.send(emailCodeSend.packageMessage(email, code));
        // 存储email和code到Redis
        String emailKey = email + "Code";
        if (!Objects.equals(redisUtils.get(emailKey), null)) {
            redisUtils.delete(emailKey);
        }
        AdminSys sys = adminSysMapper.selectOne(null);
        // 存储email，设置过期时间
        redisUtils.setex(Constants.EMAIL_CODE_KEY + email, code, sys.getEmCodeOutTime());
    }

    /***
     * 用户注册
     *
     * @param request
     * @param email
     * @param emailCode
     * @param username
     * @param password
     */
    @Override
    @Transactional
    public void register(HttpServletRequest request, String email, String emailCode, String username, String password) {
        // 获取email的值
        String emailKey = Constants.EMAIL_CODE_KEY + email;
        String RedisCode = null;
        if (Objects.equals(redisUtils.get(emailKey), null)) {
            RedisCode = redisUtils.get(emailKey).toString();
            log.info("RedisCode:{}", RedisCode);
        }

        // 如果缓存为空或者验证码比对失败
        if (Objects.equals(RedisCode, null) || !Objects.equals(RedisCode, emailCode)) {
            throw new ConditionException(MessageConstant.EMAIL_CODE_ERROR_OR_TIME_OUT);
        }

        // 就是用户名只有大小写的区别也不能注册
        if (StringUtils.isNotBlank(username)) {
            username = username.toLowerCase(); // 将关键字转换为小写
        }

        LambdaQueryWrapper<Email> wpByEmail = new LambdaQueryWrapper<>();
        LambdaQueryWrapper<User> wpByUsername = new LambdaQueryWrapper<>();
        wpByEmail.eq(Email::getEmail, email);
        wpByUsername.eq(User::getUsername, username);
        List<Email> emails = emailMapper.selectList(wpByEmail);
        List<User> userList = userMapper.selectList(wpByUsername);

        // 如果邮箱不为空
        if (!emails.isEmpty()) {
            throw new ConditionException(MessageConstant.EMAIL_EXIST);
        }

        // 如果用户不为空
        if (!userList.isEmpty()) {
            throw new ConditionException(MessageConstant.USERNAME_EXIST);
        }

        Email email1 = new Email();
        email1.setEmail(email);
        emailMapper.insert(email1);

        User user = new User();
        user.setUsername(username);
        user.setEmailId(email1.getEmailId());
        // MD5加密
        String md5Password = PasswordEncrypt.getEncryptPassword(password);
        user.setPassword(md5Password);
        user.setStatus(1);
        user.setAvatar(Constants.DEFAULT_AVATAR);

        user.setTotalSpace(
                StringTools.convertMBToBytes(adminSysMapper.selectOne(null).getUserInitUseSpace()));
        user.setLoginStatus(0);

        String ip = com.fy.utils.IpUtils.getClientIp(request);
        String positionDetail = com.fy.utils.IpUtils.getDetailedAddressByIp(ip);
        if (Objects.equals(positionDetail, null)) {
            positionDetail = "其他地区";
        }
        user.setPosition(positionDetail);
        user.setPoint(0L);
        log.info("注册用户ip:{}", ip);
        log.info("注册用户地址:{}", positionDetail);
        log.info("user:{}", user);
        int result = userMapper.insert(user);
        log.info("result:{}", result);

        String position = com.fy.utils.IpUtils.getDetailedAddressByIp(ip);
        LambdaQueryWrapper<Position> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Position::getName, position);

        Position dbPosition = positionMapper.selectOne(wrapper);
        Position ps = new Position();

        ps.setName(position);
        ps.setValue(1);
        if (Objects.equals(dbPosition, null)) {
            positionMapper.insert(ps);
        } else {
            LambdaUpdateWrapper<Position> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.eq(Position::getName, position)
                    .setSql("value = value + 1");
            positionMapper.update(null, updateWrapper);
        }

        redisUtils.delete(emailKey);
        log.info("插入用户信息:{}", user);
    }

    /**
     * 用户登录
     *
     * @param request  请求对象
     * @param email    邮箱(可选)
     * @param username 用户名(可选)
     * @param password 密码
     * @return 登录用户信息
     */
    @Override
    public LoginUserVO login(HttpServletRequest request, String email, String username, String password) {
        // 构建查询条件
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();

        // 根据登录方式选择查询条件
        if (StringUtils.isNotBlank(email)) {
            // 邮箱登录
            Integer emailId = emailMapper.getEmailIdByEmail(email);
            if (emailId == null) {
                throw new ConditionException("邮箱不存在");
            }
            queryWrapper.eq(User::getEmailId, emailId);
        } else if (StringUtils.isNotBlank(username)) {
            // 用户名登录
            queryWrapper.eq(User::getUsername, username);
        } else {
            throw new ConditionException("请输入邮箱或用户名");
        }

        // 密码校验
        // queryWrapper.eq(User::getPassword,
        // StringTools.getPasswordDD5String(password));
        User user = userMapper.selectOne(queryWrapper);
        log.info("user:{}", user);
        ExceptionHandler.throwIf(user == null, MessageConstant.USER_NOT_FOUND);

        String md5Password = PasswordEncrypt.getEncryptPassword(password);
        String dataPassword = user.getPassword();
        log.info("md5Password:{}", md5Password);
        log.info("dataPassword:{}", dataPassword);
        int status = user.getStatus();
        ExceptionHandler.throwIf(AccountStatusEnum.DISABLED.getCode() == status,
                MessageConstant.ACCOUNT_DEACTIVATED_ERROR);
        ExceptionHandler.throwIf(!Objects.equals(md5Password, dataPassword), MessageConstant.PASS_WORD_ERROR);

        // 更新登录状态和时间
        user.setLoginStatus(1);
        user.setLastLoginTime(new Date());
        userMapper.updateById(user);

        // 转换为登录用户VO
        LoginUserVO loginUserVO = new LoginUserVO();
        loginUserVO.setId(Long.valueOf(user.getUserId()));
        loginUserVO.setNickName(user.getUsername());
        loginUserVO.setUserId(emailMapper.selectById(user.getEmailId()).getEmail());
        loginUserVO.setAdmin(user.isAdmin());
        loginUserVO.setAvatar(user.getAvatar());

        return loginUserVO;
    }

    /**
     * 修改密码
     *
     * @param userName
     * @param password
     */
    @Override
    public void updatePassword(String userName, String password) {
        LambdaUpdateWrapper<User> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        lambdaUpdateWrapper.eq(User::getUsername, userName).set(User::getPassword, password);
        int rows = userMapper.update(null, lambdaUpdateWrapper);
        if (rows == 0) {
            throw new ConditionException(MessageConstant.UNKNOWN_ERROR);
        }
    }

    /**
     * 重置密码
     *
     * @param email
     * @param newPassword
     */
    @Override
    public void resetPwd(String email, String emailCode, String newPassword) {
        // 获取code的值
        String emailCodeKey = email + "Code";
        String code = (String) redisUtils.get(emailCodeKey);

        // 如果缓存为空或者验证码比对失败
        if (code == null || !Objects.equals(emailCode, code)) {
            throw new ConditionException(MessageConstant.EMAIL_CODE_ERROR_OR_TIME_OUT);
        }

        LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(User::getEmailId, email);
        User user = userMapper.selectOne(lambdaQueryWrapper);

        if (user.getStatus() == 0) {
            throw new ConditionException(MessageConstant.ACCOUNT_DEACTIVATED_ERROR + " " + "@QQ:"
                    + com.fy.utils.StringTools.getEmailPrefix(appConfig.getAdminEmails()));
        }
        LambdaUpdateWrapper<User> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(User::getEmailId, user.getEmailId())
                .set(User::getPassword, newPassword);
        userMapper.update(null, updateWrapper);
    }

    /**
     * 获取用户空间信息
     *
     * @param nickName
     * @return
     */
    @Override
    public UserSpaceVO getUserSpace(String nickName) {
        UserSpaceVO userSpaceVO;
        String userSpaceKey = nickName + "Space";
        try {
            // 先清除可能存在的错误数据
            redisTemplate.delete(userSpaceKey);

            // 从数据库获取数据
            userSpaceVO = userMapper.selectSpaceByUserName(nickName);
            log.info("从数据库获取空间信息:{}", userSpaceVO);

            if (userSpaceVO != null) {
                // 重新存入Redis
                redisTemplate.opsForValue().set(userSpaceKey, userSpaceVO, 20, TimeUnit.MINUTES);
            }

            return userSpaceVO;
        } catch (Exception e) {
            log.error("Redis操作异常，直接从数据库获取", e);
            return userMapper.selectSpaceByUserName(nickName);
        }
    }

    /**
     * 更新头像
     *
     * @param userEmail
     * @param avatar
     * @return
     */
    @Override
    public String updateAvatarPath(String userEmail, MultipartFile avatar) {

        String avatarPath = aliOssFileOperation.loadAvatar(avatar, userEmail);
        if (!avatarPath.isEmpty()) {
            Integer emailId = emailMapper.getEmailIdByEmail(userEmail);

            LambdaUpdateWrapper<User> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.eq(User::getEmailId, emailId).set(User::getAvatar, avatarPath);
            int row = userMapper.update(null, updateWrapper);
            log.info("更新到数据库的头像路径:{}", avatarPath);
            log.info("更新头像影响行数:{}", row);
        }
        return avatarPath;
    }

    /**
     * 获取头像
     *
     * @param userEmail
     * @return
     */
    @Override
    public String getAvatar(String userEmail) {

        Integer emailId = emailMapper.getEmailIdByEmail(userEmail);

        LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(User::getEmailId, emailId);
        User user = userMapper.selectOne(lambdaQueryWrapper);
        String avatarPath = user.getAvatar();
        log.info("获取到的数据库的头像地址为:{}", avatarPath);
        return avatarPath;
    }

    /**
     * 退出登录用户更新登陆状态
     *
     * @param username
     */
    @Override
    @Transactional
    public void logout(String username) {
        // 设置登陆状态
        LambdaUpdateWrapper<User> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(User::getUsername, username)
                .set(User::getLoginStatus, false);
        userMapper.update(null, wrapper);
        LocalDateTime dateTime = LocalDateTime.now();

        // 设置登陆状态
        LambdaUpdateWrapper<User> wrapper1 = new LambdaUpdateWrapper<>();
        wrapper1.eq(User::getUsername, username)
                .set(User::getLastLoginTime, dateTime);
        userMapper.update(null, wrapper1);
    }

    /**
     * 管理员获取用户列表
     *
     * @param adminLoadUserListDTO
     * @return
     */
    @Override
    public PageResult loadUserList(AdminLoadUserListDTO adminLoadUserListDTO) {
        // 1. 处理分页参数
        long pageSize = adminLoadUserListDTO != null && StringUtils.isNotBlank(adminLoadUserListDTO.getPageSize())
                ? Long.parseLong(adminLoadUserListDTO.getPageSize())
                : 15L; // 默认1页有15条数据

        long pageNo = adminLoadUserListDTO != null && StringUtils.isNotBlank(adminLoadUserListDTO.getPageNo())
                ? Long.parseLong(adminLoadUserListDTO.getPageNo())
                : 1L; // 默认为第1页

        IPage<User> page = new Page<>(pageNo, pageSize);

        // 2. 构建查询条件
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.ne("is_admin", 1);

        // 3. 安全地添加查询条件
        if (adminLoadUserListDTO != null) {
            if (StringUtils.isNotBlank(adminLoadUserListDTO.getStatus())) {
                // 判断状态并且转换成整数形式
                Integer status = Integer.parseInt(adminLoadUserListDTO.getStatus());
                queryWrapper.eq("status", status);
            }

            if (StringUtils.isNotBlank(adminLoadUserListDTO.getNickNameFuzzy())) {
                queryWrapper.like("username", adminLoadUserListDTO.getNickNameFuzzy().toLowerCase());
            }
        }

        // 4. 执行查询
        userMapper.selectPage(page, queryWrapper);
        List<User> userList = page.getRecords();

        // 5. 转换结果
        List<AdminLoadUserListVO> voList = new ArrayList<>();
        if (userList != null) {
            for (User user : userList) {
                if (user != null) {
                    AdminLoadUserListVO vo = new AdminLoadUserListVO();
                    vo.setUserId(user.getUserId());
                    vo.setNickName(user.getUsername() != null ? user.getUsername() : "");

                    // 安全地获取邮箱信息
                    Integer emailId = user.getEmailId();
                    if (emailId != null) {
                        Email email = emailMapper.selectById(emailId);
                        vo.setEmail(email != null ? email.getEmail() : "");
                    } else {
                        vo.setEmail(""); // 设置默认值
                    }

                    vo.setQqAvatar(user.getAvatar() != null ? user.getAvatar() : "");

                    // 安全地处理时间
                    if (user.getCreateTime() != null) {
                        try {
                            String creatTimeYMD = DateFormatter.getYMDhmsFormatterStringByCST(
                                    String.valueOf(user.getCreateTime()));
                            vo.setJoinTime(creatTimeYMD);
                        } catch (Exception e) {
                            log.error("日期格式化失败", e);
                            vo.setJoinTime("");
                        }
                    }

                    // 安全地处理最后登录时间
                    if (user.getLastLoginTime() != null) {
                        try {
                            String lastLoginTimeYMD = DateFormatter.getYMDhmsFormatterStringByCST(
                                    String.valueOf(user.getLastLoginTime()));
                            vo.setLastLoginTime(lastLoginTimeYMD);
                        } catch (Exception e) {
                            log.error("日期格式化失败", e);
                            vo.setLastLoginTime("");
                        }
                    }

                    // 安全地处理空间信息
                    vo.setUseSpace(user.getUseSpace() != null ? user.getUseSpace() : 0L);
                    vo.setTotalSpace(user.getTotalSpace() != null ? user.getTotalSpace() : 0L);
                    vo.setStatus(user.getStatus() != null ? user.getStatus() : 0);

                    voList.add(vo);
                }
            }
        }

        // 6. 构建返回结果
        PageResult pageResult = new PageResult();
        pageResult.setTotalCount(page.getTotal());
        pageResult.setPageNo(page.getCurrent());
        pageResult.setPageSize(page.getSize());
        pageResult.setPageTotal(page.getPages());
        pageResult.setList(voList);

        return pageResult;
    }

    /**
     * 注销账号
     *
     * @param loginUserVO
     */
    @Override
    @Transactional
    public void destroy(LoginUserVO loginUserVO) {
        String userName = loginUserVO.getNickName();
        String userEmail = loginUserVO.getUserId();
        int userId = userMapper.selectUserIdByName(userName);

        // 先删file再删user再删email--释放空间，清理redis，oss

        LambdaQueryWrapper<FileInfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(FileInfo::getUserId, userId);
        List<FileInfo> allFileList = fileInfoMapper.selectList(wrapper);

        for (FileInfo info : allFileList) {
            if (Objects.equals(info.getFolderType(), FileFolderTypeEnums.FILE.getType())) {
                // 删除阿里云存储信息
                String objectName = info.getFileObjectName();
                int count = fileInfoMapper.countByCondition(FileDelFlagEnums.USING.getFlag(),
                        FileDelFlagEnums.RECYCLE.getFlag(), objectName, userId);
                if (count > 0) {
                    aliOssFileOperation.deleteFile(objectName);
                }
            }
        }

        aliOssFileOperation
                .deleteFile(com.fy.utils.StringTools.extractFileName(userMapper.selectById(userId).getAvatar()));

        // 删除文件数据
        fileInfoMapper.delete(new QueryWrapper<FileInfo>().eq("user_id", userId));

        // 删除用户数据
        userMapper.deleteById(userId);

        // 删除邮箱信息
        LambdaQueryWrapper<Email> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Email::getEmail, userEmail);
        emailMapper.delete(lambdaQueryWrapper);
    }

    /**
     * 用户签到
     *
     * @param userId
     * @return
     */
    @Override
    @Transactional
    public Result checkIn(Integer userId) {
        // 检查今日是否已签到
        LambdaQueryWrapper<UserSign> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserSign::getUserId, userId)
                .apply("DATE(sign_time) = CURDATE()");
        Long count = userSignMapper.selectCount(queryWrapper);

        if (count > 0) {
            return Result.error("今日已签到");
        }

        // 保存签到记录
        UserSign userSign = new UserSign();
        userSign.setUserId(userId);
        userSign.setSignTime(new Date());
        userSignMapper.insert(userSign);

        // 增加用户积分
        User user = userMapper.selectById(userId);
        user.setPoint(user.getPoint() + 10); // 每次签到加10积分
        log.info("用户:{}", user);
        userMapper.updateById(user);

        return Result.success("签到成功");
    }

    /**
     * 获取用户签到信息
     *
     * @param userId 用户ID
     * @return 签到信息
     */
    @Override
    public Result<CheckInVO> getDailyCheck(Integer userId) {
        CheckInVO checkInVO = new CheckInVO();

        // 1. 检查今日是否已签到
        LambdaQueryWrapper<UserSign> todayQuery = new LambdaQueryWrapper<>();
        todayQuery.eq(UserSign::getUserId, userId)
                .apply("DATE(sign_time) = CURDATE()");
        checkInVO.setChecked(userSignMapper.selectCount(todayQuery) > 0);

        // 2. 计算连续签到天数
        int continuousDays = 0;
        Date today = new Date();
        Date checkDate = today;

        while (true) {
            LambdaQueryWrapper<UserSign> dateQuery = new LambdaQueryWrapper<>();
            dateQuery.eq(UserSign::getUserId, userId)
                    .apply("DATE(sign_time) = DATE({0})", checkDate);

            if (userSignMapper.selectCount(dateQuery) == 0) {
                break;
            }

            continuousDays++;
            // 检查前一天
            checkDate = DateUtils.addDays(checkDate, -1);
        }

        checkInVO.setContinuousDays(continuousDays);

        // 3. 计算使用天数
        User user = userMapper.selectById(userId);
        long useDays = (today.getTime() - user.getCreateTime().getTime()) / (1000 * 60 * 60 * 24);
        checkInVO.setUseDays(Math.toIntExact(useDays));

        return Result.success(checkInVO);
    }

    /**
     * 获取活跃用户排行
     *
     * @return 活跃用户列表
     */
    @Override
    public Result<List<ActiveUserVO>> getActiveUsers() {
        // 查询积分前10的用户
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.orderByDesc(User::getPoint) // 按积分降序
                .last("LIMIT 10"); // 限制返回10条记录
        List<User> users = userMapper.selectList(queryWrapper);

        // 转换为VO对象
        List<ActiveUserVO> activeUsers = users.stream().map(user -> {
            ActiveUserVO vo = new ActiveUserVO();
            vo.setNickName(user.getUsername());
            vo.setPoints(Math.toIntExact(user.getPoint()));
            vo.setAvatar(user.getAvatar());
            return vo;
        }).collect(Collectors.toList());

        return Result.success(activeUsers);
    }

    @Override
    public Result getUserProfile(Integer userId) {
        // 1. 查询用户信息
        User user = userMapper.selectById(userId);
        if (user == null) {
            return Result.error("用户不存在");
        }

        // 2. 转换为VO对象
        UserProfileVO userProfileVO = new UserProfileVO();

        if (Objects.equals(user.getSpaceAuth(), 0)) {
            userProfileVO.setAvatar(user.getAvatar());
            userProfileVO.setUsername(user.getUsername());
            userProfileVO.setPoint(Math.toIntExact(user.getPoint()));
            return Result.success(userProfileVO);
        }

        userProfileVO.setUserId(user.getUserId());
        userProfileVO.setUsername(user.getUsername());
        userProfileVO.setAvatar(user.getAvatar());
        userProfileVO.setPosition(user.getPosition());
        userProfileVO.setPoint(Math.toIntExact(user.getPoint()));
        userProfileVO.setCreateTime(user.getCreateTime());
        userProfileVO.setLastLoginTime(user.getLastLoginTime());
        userProfileVO.setUseSpace(user.getUseSpace());
        userProfileVO.setTotalSpace(user.getTotalSpace());
        userProfileVO.setDescription(user.getDescription());
        userProfileVO.setSpaceAuth(user.getSpaceAuth());
        userProfileVO.setLoginStatus(Long.valueOf(user.getLoginStatus()));
        return Result.success(userProfileVO);
    }

    @Override
    public void updateSpacePermission(Long userId, Boolean spaceEnabled) {
        User user = new User();
        user.setUserId(Math.toIntExact(userId));
        user.setSpaceAuth(spaceEnabled ? 1 : 0);
        user.setUpdateTime(new Date());
        // 使用 MyBatis Plus 更新
        this.updateById(user);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public UserInfoVO updateUserInfo(Long userId, String username, String password, String description) {
        User user = new User();
        user.setUserId(Math.toIntExact(userId));
        user.setUpdateTime(new Date());

        // 更新用户名
        if (StringUtils.isNotBlank(username)) {
            // 检查用户名是否已存在
            LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(User::getUsername, username)
                    .ne(User::getUserId, userId);
            if (userMapper.selectCount(queryWrapper) > 0) {
                throw new ConditionException("用户名已存在");
            }
            user.setUsername(username);
        }

        // 更新密码
        if (StringUtils.isNotBlank(password)) {
            // 使用已有的密码加密方法
            String encryptPwd = StringTools.getPasswordDD5String(password);
            user.setPassword(encryptPwd);
        }

        // 更新个性描述
        if (StringUtils.isNotBlank(description)) {
            user.setDescription(description);
        }

        // 使用 MyBatis Plus 更新
        this.updateById(user);
        UserInfoVO userInfoVO = new UserInfoVO();
        copyProperties(user, userInfoVO);
        return userInfoVO;
    }

}
